package cn.zch.soft.util.img2hex;
/***
 * @class ReadColorTest
 * @description TODO
 * @author zch
 * @date 2019/7/19
 * @version V0.0.1.201907191512.01
 * @function
 * @modfiyDate
 * @createDate
 * @package
 */
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ImgColorRgbRead {
  private static final Logger myLog = Logger.getRootLogger();
  /**
   * 读取一张图片的RGB值
   */
  public void getImagePixel(String image) {
    try {
      int[] rgb = new int[3];
      BufferedImage bi = getBufferedImage(image);
      int width = 0;
      int height = 0;
      int minx = 0;
      int miny = 0;
      if (bi != null) {
        width = bi.getWidth();
        height = bi.getHeight();
        minx = bi.getMinX();
        miny = bi.getMinY();
      }
      myLog.info("width=" + width + ",height=" + height + ".");
      myLog.info("minx=" + minx + ",miniy=" + miny + ".");
      for (int i = minx; i < width; i++) {
        for (int j = miny; j < height; j++) {
          // 下面三行代码将一个数字转换为RGB数字
          int pixel = bi.getRGB(i, j);
          rgb[0] = (pixel & 0xff0000) >> 16;
          rgb[1] = (pixel & 0xff00) >> 8;
          rgb[2] = (pixel & 0xff);
          myLog.info("i=" + i + ",j=" + j + ":(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")");
        }
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  /**
   * 返回屏幕色彩值
   */
  public int getScreenPixel(int x, int y) throws AWTException {
    // 函数返回值为颜色的RGB值。
    // java.awt.image包中的类，可以用来抓取屏幕，即截屏。
    Robot rb = null;
    rb = new Robot();
    // 获取缺省工具包
    Toolkit tk = Toolkit.getDefaultToolkit();
    // 屏幕尺寸规格
    Dimension di = tk.getScreenSize();
    myLog.info(di.width);
    myLog.info(di.height);
    Rectangle rec = new Rectangle(0, 0, di.width, di.height);
    BufferedImage bi = rb.createScreenCapture(rec);
    int pixelColor = bi.getRGB(x, y);
    Raster raster = bi.getData();
    int[] rgb = new int[3];
    rgb[0] = (pixelColor & 0xff0000) >> 16;
    rgb[1] = (pixelColor & 0xff00) >> 8;
    rgb[2] = (pixelColor & 0xff);
    myLog.info(rgb[0] + "," + rgb[1] + "," + rgb[2]);
    // pixelColor的值为负，经过实践得出：加上颜色最大值就是实际颜色值。
    return 16777216 + pixelColor;
  }
  /**
   * 二维码取模 来自于c# https://github.com/bestyize/PictureFetcher
   */
  public static String readHexRgbColor(BufferedImage bi) {
    int[] rgb = new int[3];
    try {
      StringBuilder newString = new StringBuilder();
      int pixel = 0;
      byte ch = 0;
      if (null != bi) {
        List<Byte> byteList = new ArrayList<>();
        for (int page = 0; page < 8; page++) {
          for (int i = 0; i < 64; i++) {
            for (int j = page * 8; j < page * 8 + 8; j++) {
              pixel = bi.getRGB(i, j);
              rgb[0] = (pixel & 0xff0000) >> 16;
              rgb[1] = (pixel & 0xff00) >> 8;
              rgb[2] = (pixel & 0xff);
              if ((rgb[0] + rgb[1] + rgb[2]) < 300) {
                pixel = 1;
              }
              else {
                pixel = 0;
              }
              if (j % 8 == 0) {
                String hexStr = Integer.toHexString(ch & 0xFF);
                if (hexStr.length() < 2) {
                  hexStr = "0" + hexStr;
                }
                newString.append(hexStr);
                ch = 0;
              }
              if (pixel == 1) {
                ch |= (byte) (1 << (j % 8));
              }
            }
          }
          //newString += "\r\n";
        }
        return newString.toString().toUpperCase();
      }
      else {
        return null;
      }
    }
    catch (Exception e) {
      myLog.error(e.getMessage(), e);
      return null;
    }
  }
  /**
   * 读取 BufferedImage
   *
   * @param image String image
   * @return BufferedImage
   */
  public static BufferedImage getBufferedImage(String image) {
    File file = new File(image);
    BufferedImage bi = null;
    try {
      bi = ImageIO.read(file);
      return bi;
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * @param args main
   */
  public static void main(String[] args) throws Exception {
    BufferedImage bi = getBufferedImage("E:\\nihao.png");
    String hexRgbStr = readHexRgbColor(bi);
    myLog.info(hexRgbStr);
  }
  /**
   * test
   */
  public void testGetScreenPixel() {
    try {
      ImgColorRgbRead rc = new ImgColorRgbRead();
      // half-white-half-black.png
      // 获取屏幕颜色值
      int x = 0;
      // 105,186,205
      x = rc.getScreenPixel(458, 98);
      myLog.info(x + " - ");
    }
    catch (AWTException e) {
      e.printStackTrace();
    }
  }
  public void testGetImgPixel() {
    try {
      ImgColorRgbRead rc = new ImgColorRgbRead();
      // 获取图片RGB
      rc.getImagePixel("E:\\half-white-half-black.png");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
